#include "mainscene.h"
#include "ui_mainscene.h"
#include "scenemanager.h"
#include <QPainter>
#include <QTimer>
#include <QKeyEvent>
#include <QDebug>
MainScene::MainScene(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainScene)
{
    ui->setupUi(this);
    _camera.updateBackgroundSize(MapManager::instance().backgroundSize());
    _camera.toCenter();

    initTimer();

    MapManager::instance().initMap(this);

    etimer.start();
    ui->widget_view->move(0, 0);
    resize(1440, 900);

    // 准备搜索数据
    QStringList searchData;
    MapManager::instance().getSearchData(searchData);

    // 创建模型
    model = new QStringListModel(searchData, this);

    // 创建完成器
    completer = new QCompleter(model, this);
    completer->setCaseSensitivity(Qt::CaseInsensitive);    // 不区分大小写
    completer->setFilterMode(Qt::MatchContains);           // 包含匹配
    completer->setMaxVisibleItems(8);                      // 最多显示8个选项

    // 绑定到搜索框
    ui->lineEdit_search_src->setCompleter(completer);
    ui->lineEdit_search_dst->setCompleter(completer);

    connect(&MapManager::instance()._findpathThread, &FindpathThread::findPath, this, [=](int path){
        _paths[path] = MapManager::instance().getPath(path);
        if(_select == path) createPaths(_paths[path]);
    });
}

MainScene::~MainScene()
{
    delete ui;
}

void MainScene::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    _camera.setCamera(painter);
    MapManager::instance().paint(painter);
}

void MainScene::resizeEvent(QResizeEvent *)
{
    _camera.updateWindowSize(size());
}

void MainScene::keyPressEvent(QKeyEvent *event)
{
    int key = event->key();
    if(key == Qt::Key_W){
        _camera.updatePosition({0, -10});
    } else if(key == Qt::Key_S){
        _camera.updatePosition({0, 10});
    } else if(key == Qt::Key_A){
        _camera.updatePosition({-10, 0});
    } else if(key == Qt::Key_D){
        _camera.updatePosition({10, 0});
    }
}

void MainScene::mousePressEvent(QMouseEvent *event)
{
    if(!_mousepressed && event->button() == Qt::LeftButton){
        _mousepressed = true;
        QPointF pos = _camera.windowToGlobal(event->pos());
        qDebug() << pos;
        _node = MapManager::instance().findNodeAt(pos);
        if(_node != nullptr && _nodecanmove){
            qDebug() << "节点被点击";
            etimer.restart();
        }
        _oldmousepos = event->pos();
    }
    QWidget::mousePressEvent(event);
}

void MainScene::mouseMoveEvent(QMouseEvent *event)
{
    if(_mousepressed){
        if(_nodecanmove && _node){
            _node->pos = _camera.windowToGlobal(event->pos());
        } else {
            // _oldmousepos - event->pos() 就是需要调整的距离
            _camera.updatePosition(_oldmousepos - event->pos());
            _oldmousepos = event->pos();
        }
    }
    QWidget::mouseMoveEvent(event);
}

void MainScene::mouseReleaseEvent(QMouseEvent *event)
{
    _mousepressed = false;
    if(_node != nullptr){
        QString line (_node->name);
        for(auto& e : _node->line) line += "," + e;
        ui->label_curselect->setText(line);
        ui->label_cur->setText(line);
        _node_id = _node->id;
        _node = nullptr;
    }
    QWidget::mouseReleaseEvent(event);
}

void MainScene::wheelEvent(QWheelEvent *event)
{
    _d_wheel = event->angleDelta().y();
    if(!_timer_wheel->isActive()) _timer_wheel->start(33);
}

void MainScene::showEvent(QShowEvent *event)
{

    QString message = SceneManager::instance()._message;
    qDebug() << "Message = " << message;
    if(message == "modify"){
        ui->widget_modify->show();
        ui->widget_view->hide();

    } else{
        ui->widget_modify->hide();
        _nodecanmove = false;
        _node = nullptr;
        ui->pushButton->setText("不可拖动节点");
        ui->widget_view->show();
    }

    QWidget::showEvent(event);
}

void MainScene::initTimer()
{
    _timer_updateui = new QTimer(this);
    connect(_timer_updateui, &QTimer::timeout, this, [=]{ update(); });
    _timer_updateui->start(16); // 60 帧, 刷屏

    _timer_wheel = new QTimer(this);
    connect(_timer_wheel, &QTimer::timeout, this, [this]{
        if(_d_wheel > 0) _camera.updateScale(_camera.scale() + 0.05);
        else if(_d_wheel < 0) _camera.updateScale(_camera.scale() - 0.05);
        _d_wheel = 0;
    });
}

void MainScene::on_pushButton_clicked()
{
    if(_nodecanmove){
        _nodecanmove = false;
        _node = nullptr;
        ui->pushButton->setText("不可拖动节点");
    }
    else {
        _nodecanmove = true;
        ui->pushButton->setText("可拖动节点");
    }
}

void MainScene::on_pushButton_2_clicked()
{
    QString src = ui->label_src->text();
    QString dst = ui->label_dst->text();
    QString line = ui->lineEdit_line->text();
    if(src.isEmpty() || dst.isEmpty())return;
    MapManager::instance().connect(_src_id, _dst_id, line);
}

void MainScene::on_pushButton_3_clicked()
{
    if(ui->label_cur->text().isEmpty())return;
    _src_id = _node_id;
    ui->label_src->setText(ui->label_cur->text());
}

void MainScene::on_pushButton_4_clicked()
{
    if(ui->label_cur->text().isEmpty())return;
    _dst_id = _node_id;
    ui->label_dst->setText(ui->label_cur->text());
}

void MainScene::on_pushButton_5_clicked()
{
    QString src = ui->label_src->text();
    QString dst = ui->label_dst->text();
    if(src.isEmpty() || dst.isEmpty())return;
    MapManager::instance().disconnect(_src_id, _dst_id);
}

void MainScene::on_pushButton_6_clicked()
{
    if(ui->label_cur->text().isEmpty() || ui->lineEdit_line->text().isEmpty())return;
    QString line = ui->lineEdit_line->text();
    MapManager::instance().erase(_node_id, line);
}

void MainScene::on_pushButton_storage_clicked()
{
    MapManager::instance().storage();

    ui->pushButton_storage->setText("已保存");
    QTimer::singleShot(3000, this, [this]{
        ui->pushButton_storage->setText("保存信息");
    });
}

void MainScene::on_pushButton_toMenu_clicked()
{
    SceneManager::instance().toNextScene(0);
}

void MainScene::on_pushButton_7_clicked()
{
    if(ui->lineEdit_search_src->text().isEmpty() || ui->lineEdit_search_dst->text().isEmpty()) return;
    QStringList srcL(ui->lineEdit_search_src->text().split('-'));
    if(srcL.size() != 2) return;
    QStringList dstL(ui->lineEdit_search_dst->text().split('-'));
    if(dstL.size() != 2) return;
    MapManager::instance().findpathbyname(srcL[0], srcL[1], dstL[0], dstL[1]);
}

void MainScene::on_radioButton_clicked(bool checked)
{
    if(checked){
        MapManager::instance().selectLine(1);
        _select = 1;
        QStringList path = MapManager::instance().getPath(1);
        if(path.size() == 0) return;
        ui->radioButton->setText("最短路径  " + path.back());
        path.pop_back();
        createPaths(path);
    } else {
        MapManager::instance().selectLine(2);
    }
}

void MainScene::on_radioButton_2_clicked(bool checked)
{
    if(checked){
        MapManager::instance().selectLine(2);
        _select = 2;
        QStringList path = MapManager::instance().getPath(2);
        if(path.size() == 0) return;
        ui->radioButton_2->setText("最少换乘  " + path.back());
        path.pop_back();
        createPaths(path);
    } else {
        MapManager::instance().selectLine(1);
    }
}

void MainScene::on_pushButton_10_clicked()
{
    if(ui->label_src->text().isEmpty() || ui->label_dst->text().isEmpty()) return;
    MapManager::instance().findpath(_src_id, _dst_id);   
}

void MainScene::on_radioButton_4_clicked(bool checked)
{
    if(checked){
        MapManager::instance().selectLine(1);
    } else {
        MapManager::instance().selectLine(2);
    }
}

void MainScene::on_radioButton_3_clicked(bool checked)
{
    if(checked){
        MapManager::instance().selectLine(2);
    } else {
        MapManager::instance().selectLine(1);
    }
}

void MainScene::on_pushButton_9_clicked()
{
    MapManager::instance().reload();
}

void MainScene::on_pushButton_8_clicked()
{
    MapManager::instance().reload();
}

#include <QVBoxLayout>
#include <QScrollArea>
void MainScene::createPaths(const QStringList &list)
{
    // 0) 清理已有布局
    QLayout *oldLayout = ui->widget_paths->layout();
    if (oldLayout) {
        QLayoutItem *item;
        while ((item = oldLayout->takeAt(0)) != nullptr) {
            if (item->widget()) delete item->widget();
            delete item;
        }
        delete oldLayout;
    }

    // 1) 新建一个主布局，设置给 ui->bodyLeft
    QVBoxLayout *mainLayout = new QVBoxLayout(ui->widget_paths);
    mainLayout->setContentsMargins(0, 0, 9, 0); // 这里一定记得设, 不然后面会有几个像素的差距

    // 2) 新建 QScrollArea 及其内部容器
    QScrollArea *scrollArea = new QScrollArea(ui->widget_paths);

    QWidget *container = new QWidget;
    QVBoxLayout *containerLayout = new QVBoxLayout(container);
    containerLayout->setSpacing(6);                   // 控件间固定 6px 间距
    containerLayout->setContentsMargins(35, 0, 0, 0);    // 左边距 35
    containerLayout->setAlignment(Qt::AlignTop);       // 布局内所有子控件顶对齐

    container->setLayout(containerLayout);

    // 3) 设置 scrollArea
    scrollArea->setWidget(container);
    scrollArea->setWidgetResizable(true);

    // 4) 最关键：将 scrollArea 加到主布局里
    mainLayout->addWidget(scrollArea);

    // 添加路线
    for(const auto& e : list){
        auto n = new QLabel(ui->widget_paths);
        n->setMinimumSize(QSize(160, 40));
        n->setMaximumSize(QSize(160, 40));
        n->setText(e);
        containerLayout->addWidget(n);
    }
}
